from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as _UserAdmin
from django.utils.translation import gettext, gettext_lazy as _
from django.contrib.auth import forms as auth_forms

from .models import Firm, User
from common.base_admin import BaseGisAdmin
from common.base_admin_site import admin_site

# Register your models here.

class FirmAdmin(admin.ModelAdmin):
    list_display = ['name', 'contact', 'mobile', 'current_user_num', 'max_user_num']
    list_editable = ['max_user_num']


COMMON_USER_FIELDSETS = (
    (None, {'fields': ('username', 'password')}),
    (_('个人信息'), {'fields': ('first_name', 'last_name', 'email')}),
    (_('权限'), {
        'fields': ('is_staff', 'is_superuser'),
    }),
    (_('默认位置'), {
        'fields': ('default_point', 'default_polygon', 'default_linestring'),
    }),
    (_('相关日期'), {'fields': ('last_login', 'date_joined')}),
)

GLOBAL_USER_FIELDSETS = (
    (None, {'fields': ('username', 'password')}),
    (_('个人信息'), {'fields': ('first_name', 'last_name', 'email')}),
    (_('权限'), {
        'fields': ('is_staff', 'is_superuser', 'global_user', 'firm'),
    }),
    (_('默认位置'), {
        'fields': ('default_point', 'default_polygon', 'default_linestring'),
    }),
    (_('相关日期'), {'fields': ('last_login', 'date_joined')}),
)

class MyUserCreationForm(auth_forms.UserCreationForm):
    def save(self, commit=True):
        if self.request is not None and not self.request.user.global_user and hasattr(self.instance, 'firm_id'):
            self.instance.firm_id = self.request.user.firm_id
        return super().save(commit)


class UserAdmin(_UserAdmin, BaseGisAdmin):
    add_form = MyUserCreationForm
    def get_fieldsets(self, request, obj=None):
        if not obj:
            return self.add_fieldsets
        if request.user.global_user:
            return GLOBAL_USER_FIELDSETS
        else:
            return COMMON_USER_FIELDSETS


admin_site.register(User, UserAdmin)
admin_site.register(Firm, FirmAdmin)